/*
 *  @Title JsonUtils.java
 *  @Package： com.phoenix.core.util
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.core.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import com.phoenix.core.logger.SimpleLogger;
import com.phoenix.orm.page.Page;

/**
 *  @ClassName JsonUtils
 *  @Description 转换工具类
 *  @author liuwb
 *  @version 1.0
 *  @date 2017年6月6日
 */
public class JsonUtils {

	private static SimpleLogger logger = SimpleLogger.getLogger(JsonUtils.class);

	static final String totalStr = "\"count\":", split = ",", rowStr = "\"data\":", jbegin = "{", jend = "}",
			jsbegin = "[", jsend = "]", suceStr = "\"success\":true";

	static final String sucessStr = "{\"success\":true}";

	static final String failStr = "{\"success\":false}";

	static final String nullStr = "{\"success\":false,data:\"\"}";

	/**
	 * 返回正常响应
	 */
	public static String buildJsonRtnSuc() {
		return sucessStr;
	}

	/**
	 * 返回空响应
	 */
	public static String nullJson() {
		return nullStr;
	}

	/**
	 * 返回对应格式的消息
	 * 
	 * @param eroStr
	 *            消息内容
	 * @return json格式数据
	 */
	public static String buildJsonRtnEro(String eroStr) {
		if (StringUtils.isBlank(eroStr)) {
			return failStr;
		}
		StringBuffer rtn = new StringBuffer("{\"success\":false,\"msg\":\"");
		return rtn.append(eroStr).append("\"}").toString();
	}

	public static String buildJsonRtnSuc(String str) {
		StringBuffer rtn = new StringBuffer("{\"success\":true,\"msg\":\"");
		return rtn.append(str).append("\"}").toString();
	}

	public static String buildJsonRtnOne(Object obj) {
		StringBuffer rtn = new StringBuffer("{\"success\":true,\"data\":[");
		return rtn.append(writeJsonAsString(obj)).append("]}").toString();
	}

	/**
	 * 将Json字符串转换成对象
	 * 
	 * @param <T>
	 * @param jsonStr
	 *            待转换的数据对象
	 * @return 返回Json数据格式
	 */
	public static <T> T readJson(String jsonStr, Class<T> classType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(jsonStr, classType);
		} catch (JsonGenerationException e) {
			logger.error("readJson JsonGenerationException", e);
		} catch (JsonMappingException e) {
			logger.error("readJson JsonMappingException", e);
		} catch (IOException e) {
			logger.error("readJson IOException", e);
		}
		return null;
	}

	/**
	 * 将json字符串转成泛型的集合类
	 * 
	 * @param jsonStr
	 *            json字符串
	 * @param collectionClass
	 *            集合类类型
	 * @param elementClass
	 *            泛型类型
	 * @param <E>
	 *            泛型
	 */
	public static <E> Collection<E> readJsonAsCollectionType(String jsonStr,
			Class<? extends Collection<E>> collectionClass, Class<E> elementClass) {
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClass);
		try {
			return mapper.readValue(jsonStr, javaType);
		} catch (IOException e) {
			logger.error("readJson IOException", e);
		}
		return Collections.emptyList();
	}

	/**
	 * 将object对象转换成Json字符串
	 * 
	 * @param object
	 *            待转换的数据对象
	 * @return 返回Json数据格式
	 */
	public static String writeJsonAsString(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			mapper.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
			return mapper.writeValueAsString(object);
		} catch (JsonGenerationException e) {
			logger.error("writeJsonAsString JsonGenerationException", e);
		} catch (JsonMappingException e) {
			logger.error("writeJsonAsString JsonMappingException", e);
		} catch (IOException e) {
			logger.error("writeJsonAsString IOException", e);
		}
		return "";
	}

	/**
	 * 转换page对象
	 * 
	 * @param page
	 * @return String
	 */
	public static String jsonFormatter(Page<?> page) {
		StringBuffer jsonStr = new StringBuffer(jbegin);
		if (page == null)
			return nullJson(jsonStr);
		jsonStr.append(totalStr).append(page.getTotalCount()).append(split);
		jsonStr.append(rowStr).append(jsbegin);
		List<?> list = page.getResult();
		Object obj = null;
		for (int i = 0, j = list.size(); i < j; i++) {
			obj = list.get(i);
			jsonStr.append(writeJsonAsString(obj));
			if (i != (j - 1))
				jsonStr.append(split);
		}
		jsonStr.append(jsend).append(jend);
		return jsonStr.toString();
	}

	public static String jsonFormatterNestedPage(Page<?> page) {
		StringBuffer jsonStr = new StringBuffer(jbegin);
		if (page == null)
			return nullJson(jsonStr);
		jsonStr.append(totalStr).append(page.getTotalCount()).append(split);
		jsonStr.append(rowStr).append(jsbegin);
		List<?> list = page.getResult();
		Object obj = null;
		for (int i = 0, j = list.size(); i < j; i++) {
			obj = list.get(i);
			jsonStr.append(jsonFormatterNested(obj));
			if (i != (j - 1))
				jsonStr.append(split);
		}
		jsonStr.append(jsend).append(jend);
		return jsonStr.toString();
	}

	/**
	 * 转换list对象
	 * 
	 * @return String
	 */
	public static String jsonFormatterList(List<?> list) {
		StringBuffer jsonStr = new StringBuffer(jbegin);
		if (list == null) {
			return nullJson(jsonStr);
		}
		jsonStr.append(totalStr).append(list.size()).append(split);
		jsonStr.append(suceStr).append(split).append(rowStr).append(jsbegin);
		Object obj = null;
		for (int i = 0, j = list.size(); i < j; i++) {
			obj = list.get(i);
			jsonStr.append(writeJsonAsString(obj));
			if (i != (j - 1))
				jsonStr.append(split);
		}
		jsonStr.append(jsend).append(jend);
		return jsonStr.toString();
	}

	private static String nullJson(StringBuffer jsonStr) {
		jsonStr.append(totalStr).append(0).append(split);
		jsonStr.append(rowStr).append(jsbegin);
		jsonStr.append(jsend).append(jend);
		return jsonStr.toString();
	}

	/**
	 * 带分页的对象转换
	 * 
	 * @param obj
	 * @return String
	 */
	public static String jsonFormatterAddRows(Object obj) {
		StringBuffer jsonStr = new StringBuffer(jbegin);
		jsonStr.append(totalStr).append("0").append(split);
		jsonStr.append(rowStr).append(jsbegin);
		jsonStr.append(writeJsonAsString(obj));
		jsonStr.append(jsend).append(jend);
		return jsonStr.toString();
	}

	/**
	 * 嵌套对象转换
	 * 
	 * @param obj
	 * @return String
	 */
	public static String jsonFormatterNested(Object obj) {
		return PojoMapper.toJson(obj);
	}

}
